package com.zyz.common.redis.config;

import com.alibaba.fastjson2.JSON;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

import java.nio.charset.StandardCharsets;

/**
 * 使用fastjson来优化redis内部的json序列化和反序列化<br/>
 * 缩小存储空间 提升效率
 * @param <T>
 */
public class JsonRedisSerializer<T> implements RedisSerializer<T> {

    private Class<T> clazz;

    public JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        String string = new String(bytes, StandardCharsets.UTF_8);
        return JSON.parseObject(string,clazz);
    }
}
